import { createRoot } from 'react-dom/client'
import React, { useEffect, useRef, useState } from 'react'
import WaterfallCard from '@/components/waterfall-card'

// 计算真实高度，这里只计算除了图片的高度
async function getRealHeight(item: ItemOption, realWidth: number) {
    const dom = document.createElement('div')

    const root = createRoot(dom)
    root.render(React.createElement(WaterfallCard, { item, width: realWidth + 'px', noImage: true }))

    const height: number = dom.firstElementChild!.clientHeight
    dom.style.display = 'none'
    // document.body.removeChild(dom)
    return height
}

export const useWaterfall = () => {
    const backTop = () => {
        window.scrollTo({
            top: 0,
            behavior: 'instant'
        })
    }

    const loading = useRef(false)

    const [waterfallOption] = useState({
        bottomDistance: 0,
        // 是否只展示图片，这是自定义加的一个属性
        onlyImage: false,
        topPreloadScreenCount: 0,
        bottomPreloadScreenCount: 0,
        virtual: true,
        gap: 15,
        padding: 15,
        itemMinWidth: 220,
        minColumnCount: 2,
        maxColumnCount: 10
    })

    // 瀑布流元素高度的计算函数
    const calcItemHeight = async (item: ItemOption, itemWidth: number) => {
        let height = 0
        // 当包含图文时，需要单独计算文字部分的高度
        // 文字部分的高度 + 图片的高度 = 真实高度
        if (!waterfallOption.onlyImage) {
            height = await getRealHeight(item, itemWidth)
            return height
        }
        return item.height * (itemWidth / item.width) + height
    }

    const data = useRef({
        page: 0,
        size: 30,
        total: 0,
        max: 180,
        end: false
    })

    const [photoList, setPhotoList] = useState<ItemOption[]>([])

    const loadData = async () => {
        if (data.current.end) return
        data.current.page++
        const response = await fetch(
            `https://mock.tatakai.top/images?page=${data.current.page}&size=${data.current.size}&mode=simple`
        )
        const result = await response.json()
        if (!result.list.length) {
            data.current.end = true
            return
        }
        data.current.total = result.total
        data.current.max = result.max
        setPhotoList((pre) => [...pre, ...result.list])
    }

    // 检查是否加载更多
    const checkScrollPosition = async () => {
        if (loading.current) {
            return
        }
        const scrollHeight = document.documentElement.scrollHeight
        const scrollTop = document.documentElement.scrollTop
        const clientHeight = document.documentElement.clientHeight

        const distanceFromBottom = scrollHeight - scrollTop - clientHeight

        // 不大于最小底部距离就加载更多
        if (distanceFromBottom <= waterfallOption.bottomDistance) {
            loading.current = true
            await loadData()
            loading.current = false
        }
        requestAnimationFrame(checkScrollPosition)
    }

    useEffect(() => {
        checkScrollPosition()
    }, [])

    return {
        backTop,
        waterfallOption,
        photoList,
        calcItemHeight
    }
}
